<template>
  <div>
    <h1>login</h1>
    <form>
      <input type="text" v-model="name" />
      <br />
      <input type="text" v-model="password" />
      <br />
      <input type="submit" value="登录" @click.prevent="login" />
    </form>
  </div>
</template>

<script>
import ajax from "../api/ajax";
import jsCookie from "js-cookie";
export default {
  data() {
    return {
      name: "",
      password: ""
    };
  },
  mounted() {},
  methods: {
    async login() {
      const url = "/api/login";
      const data = {};
      data.name = this.name;
      data.password = this.password;
      // url, method = "get", data, headType
      const result = await ajax(url, "post", data, "form");
      //token最早在登录成功之后返回document.cookie   localstorage中
      // console.log(document.cookie);
      // console.log(jsCookie.get("token"));
      localStorage.setItem("token", jsCookie.get("token"));

      console.log(result);
      if (result.data.info == "登录成功！！") {
        // 将result.data.level 传值给 vuex $store state mutations actions
        const level = result.data.level;
        this.$store.dispatch("emitSaveLevel", level);
        // 当登录成功跳转到主页
        this.$router.push("/home");
      }
    }
  }
};
</script>

<style></style>
